# 导入模块
import trainer
import imgsave
import cv2 as cv
import os
import urllib
import urllib.request
import time
import threading
from tkinter import *
# 窗口创建
windows=Tk()
# 窗口大小
canvas = Canvas(windows,height=150,width=500)

#   自动录入人脸
def save1():
    name = entry.get()  # 名字获取
    num = 1
    imgPath = './jm/' # 图片路径
    imagePaths = [os.path.join(imgPath, f) for f in os.listdir(imgPath)]
    for imagePath in imagePaths:
        id = int(os.path.split(imagePath)[1].split('.')[0])
        names = str(os.path.split(imagePath)[1].split('.', 2)[1])
        if names == name:
            num = max(num, id)  # 查询之前是否有录入过
    imgsave.savea(name,num)  # 录入
    trainer.train()  # 训练

def save2():
    name = entry.get()  # 名字获取
    num = 1
    imgPath = './jm/'  # 图片路径
    imagePaths = [os.path.join(imgPath, f) for f in os.listdir(imgPath)]
    for imagePath in imagePaths:
        id = int(os.path.split(imagePath)[1].split('.')[0])
        names = str(os.path.split(imagePath)[1].split('.', 2)[1])
        if names == name:
            num = max(num, id)  # 查询之前是否有录入过
    imgsave.saves(name,num)  # 录入
    trainer.train()  # 训练


def recognize():
    recognizer = cv.face.LBPHFaceRecognizer_create()
    recognizer.read('./trainer/trainer.yml')   # 加载训练数据
    names = []

    def face_detect_demo(img):
        gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)  # 图片转为灰度
        face_detector = cv.CascadeClassifier(cv.data.haarcascades + 'haarcascade_frontalface_alt2.xml')     # 引入级联器
        face = face_detector.detectMultiScale(gray)
        for x, y, w, h in face:
            cv.rectangle(img, (x, y), (x + w, y + h), color=(0, 0, 255), thickness=2)   # 人脸识别
            ids, confidence = center = recognizer.predict(gray[y:y + h, x:x + w])
            if confidence > 50:     # 判断置信评分
                cv.putText(img, 'unknow', (x + 10, y - 10), cv.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 1)
            else:
                cv.putText(img, str(names[ids - 1]), (x + 10, y - 10), cv.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 1)
        cv.imshow('Please press the space to exit', img)

    # 获取名字
    def name():
        path = './jm/'
        # names = []
        imagePaths = [os.path.join(path, f) for f in os.listdir(path)]
        for imagePath in imagePaths:
            name = str(os.path.split(imagePath)[1].split('.', 2)[1])
            names.append(name)

    cap = cv.VideoCapture(0)    # 摄像头
    name()  # 获取名字
    while True:
        flag, frame = cap.read()    # 读取一帧画面
        if not flag:
            break
        face_detect_demo(frame)
        if ord(' ') == cv.waitKey(10):  # 退出
            break
    cap.release()   # 释放摄像头
    cv.destroyAllWindows()  # 释放内存


if __name__ == '__main__':
    windows.title("人脸识别")   # 窗口名称
    label = Label(windows,text="请输入名字,再进行人脸录入(输入英文):")  # 标签1
    entry = Entry(windows,show=None)    # 输入框
    label.place(x=20,y=20)  # 放置标签1
    entry.place(x=250,y=20)     # 放置输入框
    Button(windows, text="自动人脸录入(自动拍50张，拍完自动退出)", command=save1).place(x=20,y=50)  # 按钮1，并放置
    Button(windows, text="手动人脸录入(按s拍1张,空格退出)", command=save2).place(x=20, y=90)     # 按钮2，并放置
    Button(windows, text="开始人脸识别(空格退出)", command=recognize).place(x=300,y=50)   # 按钮3，并放置
    result = Label(windows,text="提醒：录入完在训练，会卡顿，请勿关闭").place(x=280,y=90)     # 标签2，并放置
    canvas.pack()

    windows.mainloop()